const MYSQL = require("../../sql/mysql");
// MYSQL数据库配置信息
const MYSQLConfig = require("../../sql/database");
// 角色表
let sqlName = MYSQLConfig.datasheetName.roles;
// 角色菜单权限表
let roleMenusSqlName = MYSQLConfig.datasheetName.role_menus;

const DayJs = require("dayjs");

const roleExist = require("./exist")

/**
 * 添加菜单权限
 * @param {object} params
 * @param {string} params.id 角色id
 * @param {string} params.menu 菜单id
 * @returns {Promise<{code:string,msg:string}>}
 */
module.exports = async (params = {}) => {
  let { role, menu_id } = params;

  if (!role) {
    throw { code: 500, msg: "role不能为空" };
  } else if (menu_id) {
    throw { code: 500, msg: "menu_id不能为空" };
  }

  await roleExist({id:role})

  let query = `INSERT INTO ${roleMenusSqlName} SET ? `;
  let create_date = DayJs(Date.now()).valueOf();

  try {
    await MYSQL.promise().query(query, {
      role,
      menu_id,
      create_date,
    });
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "添加菜单权限失败",
    };
  }

  return {
    code: 0,
    msg: "操作成功",
  };
};
